package com.hjj.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.entity.Product;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.entity.Search;
import com.hjj.springboot.service.IProductService;
import com.hjj.springboot.service.ISearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private ISearchService searchService;

    @Autowired
    private IProductService productService;

    @PostMapping("/save")
    public R save(@RequestBody Search search)  {
        Search resultSearch = searchService.getOne(new QueryWrapper<Search>().eq("gId", search.getGId()));
        if (resultSearch == null) {
            search.setCount(1);
            search.setLastSearchTime(new Date());
            searchService.save(search);
        } else {
            resultSearch.setCount(resultSearch.getCount() + 1);
            resultSearch.setLastSearchTime(new Date());
            searchService.updateById(resultSearch);
        }
        return R.ok("保存成功");
    }

    @GetMapping("/list")
    public R list() {
        Page<Search> pageSearch = searchService.page(new Page<>(1, 8), new QueryWrapper<Search>().orderByDesc("count").orderByDesc("lastSearchTime"));
        for (Search search : pageSearch.getRecords()) {
            Product product = productService.getById(search.getGId());
            search.setProduct(product);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("searchList", pageSearch.getRecords());
        return R.ok(map);
    }

}
